import React, { useState } from "react";
import { Form, Input, Button, Select, Card, message, Checkbox } from "antd";
import {
  UserOutlined,
  LockOutlined,
  PhoneOutlined,
  MailOutlined,
} from "@ant-design/icons";
import { useNavigate, Link } from "react-router-dom";
import { authAPI } from "../../../services/api";
import styled from "styled-components";

const RegisterContainer = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f0f2f5;
`;

const RegisterCard = styled(Card)`
  width: 100%;
  max-width: 480px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
`;

const RegisterTitle = styled.h2`
  text-align: center;
  margin-bottom: 24px;
  color: #1890ff;
`;

const LoginLink = styled.div`
  text-align: center;
  margin-top: 16px;
  color: #666;
`;

interface RegisterForm {
  username: string;
  password: string;
  confirmPassword: string;
  phone: string;
  email: string;
  role: "teacher" | "student";
  code: string;
  agree: boolean;
}

const Register: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [codeLoading, setCodeLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 发送验证码
  const sendCode = async () => {
    try {
      const phone = form.getFieldValue("phone");
      const role = form.getFieldValue("role");

      if (!phone) {
        message.warning("请先输入手机号");
        return;
      }

      if (!role) {
        message.warning("请先选择注册类型");
        return;
      }

      setCodeLoading(true);
      await authAPI.sendCode(phone, role);
      message.success("验证码已发送");

      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error) {
      console.error("发送验证码失败:", error);
      message.error("验证码发送失败");
    } finally {
      setCodeLoading(false);
    }
  };

  const onFinish = async (values: RegisterForm) => {
    try {
      setLoading(true);

      await authAPI.register({
        phone: values.phone,
        password: values.password,
        name: values.username,
        code: values.code,
        type: values.role,
        // headImg: '', // 可选头像
      });

      message.success("注册成功！请登录");
      navigate("/login");
    } catch (error) {
      console.error("注册失败:", error);
      message.error("注册失败，请检查信息后重试");
    } finally {
      setLoading(false);
    }
  };

  return (
    <RegisterContainer>
      <RegisterCard>
        <RegisterTitle>用户注册</RegisterTitle>
        <Form<RegisterForm>
          form={form}
          name="register"
          initialValues={{ role: "student" }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="role"
            rules={[{ required: true, message: "请选择注册类型" }]}
          >
            <Select size="large" placeholder="选择注册类型">
              <Select.Option value="teacher">教师</Select.Option>
              <Select.Option value="student">学生</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="username"
            rules={[
              { required: true, message: "请输入姓名" },
              { min: 2, max: 20, message: "姓名长度为2-20个字符" },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="真实姓名"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="phone"
            rules={[
              { required: true, message: "请输入手机号" },
              { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
            ]}
          >
            <Input
              prefix={<PhoneOutlined />}
              placeholder="手机号"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入正确的邮箱格式" },
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="邮箱地址"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: "请输入验证码" }]}
          >
            <Input.Group compact>
              <Input
                style={{ width: "calc(100% - 120px)" }}
                placeholder="短信验证码"
                size="large"
              />
              <Button
                style={{ width: "120px" }}
                size="large"
                onClick={sendCode}
                loading={codeLoading}
                disabled={countdown > 0}
              >
                {countdown > 0 ? `${countdown}s` : "获取验证码"}
              </Button>
            </Input.Group>
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: "请输入密码" },
              { min: 6, message: "密码至少6位" },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
                message: "密码必须包含字母和数字",
              },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="设置密码（至少6位，包含字母和数字）"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={["password"]}
            rules={[
              { required: true, message: "请确认密码" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("password") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次输入的密码不一致"));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认密码"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value
                    ? Promise.resolve()
                    : Promise.reject(new Error("请同意用户协议")),
              },
            ]}
          >
            <Checkbox>
              我已阅读并同意{" "}
              <a href="#" target="_blank">
                《用户协议》
              </a>{" "}
              和{" "}
              <a href="#" target="_blank">
                《隐私政策》
              </a>
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              size="large"
              loading={loading}
            >
              注册
            </Button>
          </Form.Item>
        </Form>

        <LoginLink>
          已有账号？ <Link to="/login">立即登录</Link>
        </LoginLink>
      </RegisterCard>
    </RegisterContainer>
  );
};

export default Register;
